resource "google_sql_database_instance" "instance" {
    provider         = google-beta
    name             = "<%= ctx[:vars]['database_instance_name'] %>"
    database_version = "POSTGRES_11"
    region           = "us-central1"
    settings {
		tier = "db-f1-micro"
	}

    deletion_protection  = "<%= ctx[:vars]['deletion_protection'] %>"
}

resource "google_sql_database" "db" {
    provider = google-beta
    instance = google_sql_database_instance.instance.name
    name     = "db"
}

resource "random_password" "pwd" {
    length = 16
    special = false
}

resource "google_sql_user" "user" {
    provider = google-beta
    name = "<%= ctx[:vars]['username'] %>"
    instance = google_sql_database_instance.instance.name
    password = random_password.pwd.result
}

resource "google_bigquery_connection" "<%= ctx[:primary_resource_id] %>" {
    provider      = google-beta
    connection_id = "<%= ctx[:vars]['connection_id'] %>"
    location      = "US"
    friendly_name = "👋"
    description   = "a riveting description"
    cloud_sql {
        instance_id = google_sql_database_instance.instance.connection_name
        database    = google_sql_database.db.name
        type        = "POSTGRES"
        credential {
          username = google_sql_user.user.name
          password = google_sql_user.user.password
        }
    }
}
